package org.exhibitj.operators.matchers;

import java.util.logging.Logger;

import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.exhibitj.defect.Defense;
import org.exhibitj.operators.FetchingRunnable;

public class ControlLocator<T> extends FetchingRunnable<T> {
	private static final Logger LOG = Logger.getLogger(ControlLocator.class.getSimpleName());
	private final Shell shell;
	private final Class<T> ofType;
	private final Matcher<T>[] matchers;

	public ControlLocator(Shell shell, Class<T> type, Matcher<T>[] matchers) {
		Defense.notNull(shell);
		Defense.notNull(type);
		Defense.notNull(matchers);
		
		this.shell = shell;
		this.ofType = type;
		this.matchers = matchers;
	}

	@SuppressWarnings("unchecked")
	@Override
	public T fetchValue() {
		for (Control each : shell.getChildren()) {
			if (ofType.isInstance(each) && matching((T)each, matchers)) {
				LOG.info("found matching control [" + ofType.getSimpleName() + "]");
				return (T)each;
			}
		}
		return null;
	}

	private boolean matching(T control, Matcher<T>[] matchers) {
		for (Matcher<T> each : matchers) {
			if (!each.isMatch(control)) {
				return false;
			}
		}
		return true;
	}
}
